package com.cheyunkeji.er.activity.evaluate;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.widget.MyEditText;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.adapter.evaluate.UploadedCarListAdapter;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.evaluate.EvaluateCarItemInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class UploadedCarActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener, TextWatcher, UploadedCarListAdapter.OnItemActionListener, AdapterView.OnItemClickListener {

    private static final String TAG = UploadedCarActivity.class.getSimpleName();

    //    每页数据量
    private static final int COUNTS_PER_PAGE = 10;

    //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
    private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

    //     当前页数
    private static int CURRENT_LOAD_PAGE = 1;
    //    搜索关键字
    private static String KEY_WORDS = null;

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    //    @BindView(R.id.iv_search)
//    ImageButton ivSearch;
//    @BindView(R.id.et_search_content)
//    EditText etSearchContent;
    @BindView(R.id.et_search_content)
    MyEditText etSearchContent;

    @BindView(R.id.tv_search_content)
    TextView tvSearchContent;
    @BindView(R.id.ll_empty_content_display)
    LinearLayout llEmptyContentDisplay;
    @BindView(R.id.swipe_target)
    ListView lvCarList;
    @BindView(R.id.swipe_layout)
    SwipeLayout swipeLayout;
    @BindView(R.id.tv_item_count)
    TextView tvItemCount;

    private ArrayList<EvaluateCarItemInfo> dataList;

    private UploadedCarListAdapter adapter;

    private Handler uiRefreshHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SwipeLayout.STATE_NORMAL:
                    if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                        onRefreshSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
                    } else {
                        onLoadMoreSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
                    }
                    break;

                case SwipeLayout.STATE_SEARCH_BY_KEYWORD:
                    if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                        onRefreshSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
                    } else {
                        onLoadMoreSuccessed((ArrayList<EvaluateCarItemInfo>) msg.obj);
                    }
                    break;
                default:
                    break;
            }
        }
    };


    /**
     * 上拉加载成功刷新
     *
     * @param newList
     */
    private void onLoadMoreSuccessed(ArrayList<EvaluateCarItemInfo> newList) {
        if (newList != null) {
            if (newList.size() != 0) {
                swipeLayout.endLoadMore();
                dataList.addAll(newList);
                adapter.notifyDataSetChanged();
                CURRENT_LOAD_PAGE++;
            } else {
                swipeLayout.endLoadMore();
                swipeLayout.setLoadMoreEnabled(false);
            }
        }
    }

    private void onRefreshSuccessed(ArrayList<EvaluateCarItemInfo> newList) {
        if (newList != null && newList.size() != 0) {
            hideEmptyView();
            dataList.clear();
            dataList.addAll(newList);
            adapter.notifyDataSetChanged();
            CURRENT_LOAD_PAGE++;
        } else if (newList.size() == 0) {
            showContentEmptyView();
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
        swipeLayout.endRefresh();
    }

    @Override
    protected void init() {
        setContentView(R.layout.er_activity_uploaded_car);
        ButterKnife.bind(this);
        KEY_WORDS = "";
        dataList = new ArrayList<>();
        adapter = new UploadedCarListAdapter(dataList, this);
        lvCarList.setAdapter(adapter);
        lvCarList.setOnItemClickListener(this);
    }

    @Override
    protected void initView() {
        vTopbar.setTitle("已上传车辆");
        vTopbar.setLeftBack();
//        ivSearch.setOnClickListener(this);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadMoreListener(this);
        etSearchContent.addTextChangedListener(this);

        etSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {
                    KEY_WORDS = etSearchContent.getText().toString().trim();
                    onRefresh();
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        swipeLayout.setRefreshing(true);
        onRefresh();
    }


    private void loadSavedEvaluateCarList(int page, int rows, final String keyWord) {
        HashMap<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        params.put("rows", String.valueOf(rows));
        params.put("state", "2");
        if (!TextUtils.isEmpty(keyWord))
            params.put("key", keyWord);
        ApiClient.postForm(HttpConstants.EVALUATE_CAR_LIST, params, new RespCallback<List<EvaluateCarItemInfo>>() {

            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg, Gravity.CENTER);
            }

            @Override
            protected void onMsgCount(int rows) {
                super.onMsgCount(rows);
                setItemCount(rows);
            }

            @Override
            protected void onSuccess(List<EvaluateCarItemInfo> data) {

                Message msg = uiRefreshHandler.obtainMessage();
                msg.what = TextUtils.isEmpty(keyWord) ? SwipeLayout.STATE_NORMAL : SwipeLayout.STATE_SEARCH_BY_KEYWORD;
                msg.obj = data;
                uiRefreshHandler.sendMessage(msg);

            }

            @Override
            public void onError(Exception e) {
                super.onError(e);

                if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                    swipeLayout.endRefresh();
                } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                    swipeLayout.endLoadMore();
                }
            }
        });
    }

    public void setItemCount(int itemCount) {
        tvItemCount.setText(String.format("共%1$s条数据", String.valueOf(itemCount)));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.iv_search:
//
//                KEY_WORDS = etSearchContent.getText().toString().trim();
//                swipeLayout.setRefreshing(true);
//                onRefresh();
//                break;


            default:
                break;
        }
    }

    private void hideEmptyView() {
        //swipeLayout.setVisibility(View.VISIBLE);
        llEmptyContentDisplay.setVisibility(View.INVISIBLE);
    }


    private void showContentEmptyView() {
        //swipeLayout.setVisibility(View.INVISIBLE);
        if (!TextUtils.isEmpty(KEY_WORDS)) {
            llEmptyContentDisplay.setVisibility(View.VISIBLE);
            tvSearchContent.setText(KEY_WORDS);
        } else {
            llEmptyContentDisplay.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onLoadMore() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
        loadSavedEvaluateCarList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
    }

    @Override
    public void onRefresh() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
        CURRENT_LOAD_PAGE = 1;
        loadSavedEvaluateCarList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE, KEY_WORDS);
        swipeLayout.setLoadMoreEnabled(true);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (TextUtils.isEmpty(s.toString())) {
            KEY_WORDS = null;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        uiRefreshHandler.removeCallbacksAndMessages(null);
    }


    @Override
    public void onDownloadClickedListener(int position) {
        Log.e(TAG, "onDownloadClickedListener: " + position);
//        SToast.show("Download Icon : " + position);
    }

    @Override
    public void onLookReportClickedListener(int position) {
        Intent intent = new Intent(this, EvaluateReportActivity.class);
        EvaluateCarItemInfo info = dataList.get(position);
        String h5 = info.getH5();
//        intent.putExtra("AID", info.getAid());
//        intent.putExtra("h5", h5);
        intent.putExtra(
                "data", new String[] {h5, info.getAid()});

        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        SToast.show("ItemClick : " + position);
        Intent intent = new Intent(this, EvaluateWorkflowActivity.class);
        intent.putExtra("AID", dataList.get(position).getAid());
        intent.putExtra(Constants.EVALUATE_ARCHIVE_TYPE, Constants.ARCHIVE_TYPE_UPLOADED_TO_EDIT);
        startActivity(intent);

        Log.e(TAG, "onItemClicked: " + dataList.get(position).getAid());
    }

}
